//
//  CategoryViewController.m
//  BaseProject
//
//  Created by 王洋 on 2020/7/1.
//  Copyright © 2020 王洋. All rights reserved.
//
#import "ZZLayout.h"
#import "ReactiveObjC/ReactiveObjC.h"

#import "MarriageProductCell.h"

#import "TT_MessageManager.h"

#import "CategoryNaviView.h"
#import "PrimaryClassificationView.h"
#import "SecondaryClassificationView.h"

#import "SearchProductViewController.h"
#import "ProductDetailViewController.h"
#import "ShopCartViewController.h"
#import "MessageCenterViewController.h"

#import "CategoryViewController.h"

@interface CategoryViewController ()<UICollectionViewDelegate, UICollectionViewDataSource, ZZLayoutDelegate, UITextFieldDelegate>

@property (nonatomic, strong) CategoryNaviView *naviView;

@property (nonatomic, strong) PrimaryClassificationView *primaryClassificationView;
@property (nonatomic, strong) SecondaryClassificationView *secondaryClassificationView;

@property (nonatomic, strong) UICollectionView *collectionView;

@property (nonatomic, strong) NSMutableArray <ProClassificationModel *>*classificationDataArray;

@property (nonatomic, strong) NSMutableArray <CommonPackageModel *> *dataArray;

@property (nonatomic, assign) NSInteger pageNum;
@property (nonatomic, assign) NSInteger pageSize;

@property (nonatomic, assign) NSInteger firSelectIndex;
@property (nonatomic, assign) NSInteger secSelectIndex;

@end

@implementation CategoryViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self initView];
//    [self refreshParam];
//    [self request_goodsList];
}

- (void)refreshParam {
    self.pageNum = 1;
    self.pageSize = 20;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
//    //有数据的时候刷新数据
//    if (self.dataArray.count > 0) {
//
//    }
    
    //没数据的时候请求数据
    if (self.classificationDataArray.count > 0) {
    } else {
        [self refreshParam];
        [self request_catData];
    }

}

#pragma mark initView
- (void)initView {
    
    self.title = @"婚品";
    self.navigationController.navigationBarHidden = YES;
    #if RT_INTERACTIVE_PUSH
        self.rt_navigationController.rt_enableInteractivePush = YES;
    #endif
    
    [RACObserve([TT_MessageManager manager], totalUnReadCount) subscribeNext:^(id x) {
        if ([TT_MessageManager manager].totalUnReadCount > 0) {
            self.naviView.msgBtn.badgeValue = [NSString stringWithFormat:@"%d",[TT_MessageManager manager].totalUnReadCount];
            self.naviView.msgBtn.badgeBGColor = [UIColor redColor];
        } else {
            self.naviView.msgBtn.badgeValue = @"";
            self.naviView.msgBtn.badgeBGColor = [UIColor clearColor];
        }
    }];
    
    [self.view addSubview:self.naviView];
    [self.view addSubview:self.primaryClassificationView];
    [self.view addSubview:self.secondaryClassificationView];
    [self.view addSubview:self.collectionView];
    
    [self.naviView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(0);
        make.top.mas_equalTo(0);
        make.height.mas_equalTo(NavBar_Height + kStatusBarHeight);
    }];
    
    [self.primaryClassificationView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(0);
        make.height.mas_equalTo([PrimaryClassificationView calculateHeight]);
        make.top.mas_equalTo(self.naviView.mas_bottom);
    }];
    
    [self.secondaryClassificationView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.mas_equalTo(0);
        make.top.mas_equalTo(self.primaryClassificationView.mas_bottom);
        make.width.mas_equalTo(88);
    }];
    
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.secondaryClassificationView.mas_right);
        make.top.mas_equalTo(self.primaryClassificationView.mas_bottom);
        make.right.bottom.mas_equalTo(0);
    }];

    [self initViewAction];
}

- (void)initViewAction {
    
    WEAKSELF
    self.primaryClassificationView.PrimaryClassificationViewBlock = ^(NSInteger index) {
        
        weakSelf.firSelectIndex = index;
        [weakSelf primaryClassificationSelectIndex:index];
    };
    
    self.secondaryClassificationView.SecondaryClassificationViewBlock = ^(NSInteger index) {
        
        weakSelf.secSelectIndex = index;
        [weakSelf secClassificationSelectIndex:index];
    };
    
    self.naviView.CategoryNaviViewBlock = ^(CategoryNaviViewType type) {
      
        switch (type) {
            case CategoryNaviViewType_im:{
                
                MessageCenterViewController *vc = [[MessageCenterViewController alloc] init];
                [weakSelf.navigationController pushViewController:vc animated:YES];
                
            } break;
            case CategoryNaviViewType_cart:{
                
                ShopCartViewController *vc = [[ShopCartViewController alloc] init];
                [weakSelf.navigationController pushViewController:vc animated:YES];
                
            } break;
            default:
                break;
        }
    };
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    
    SearchProductViewController *vc = [[SearchProductViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
    return NO;
}

//点击一级
- (void)primaryClassificationSelectIndex:(NSInteger)index {
    
    for (ProClassificationModel *primaryModel in self.classificationDataArray) {
        
        primaryModel.isSelect = NO;
        
        for (ProClassificationModel *secModel in primaryModel.sysClassificationList) {
            secModel.isSelect = NO;
        }
    }

    self.firSelectIndex = index;
    self.classificationDataArray[index].isSelect = YES;
    
    [self.primaryClassificationView fillWithArray:self.classificationDataArray];
    
    if (self.classificationDataArray[self.firSelectIndex].sysClassificationList.count > 0) {
        
        self.classificationDataArray[self.firSelectIndex].sysClassificationList.firstObject.isSelect = YES;
        self.secSelectIndex = 0;
        [self refreshParam];
        [self request_goodsList];
    } else {
        self.dataArray = @[].mutableCopy;
        [self.collectionView reloadData];
    }
    
    [self.secondaryClassificationView fillWithArray:self.classificationDataArray[self.firSelectIndex].sysClassificationList];
    

}

//点击二级
- (void)secClassificationSelectIndex:(NSInteger)index {
    
    for (ProClassificationModel *secModel in self.classificationDataArray[self.firSelectIndex].sysClassificationList) {
        secModel.isSelect = NO;
    }
    
    self.secSelectIndex = index;
    self.classificationDataArray[self.firSelectIndex].sysClassificationList[index].isSelect = YES;
    [self.secondaryClassificationView fillWithArray:self.classificationDataArray[self.firSelectIndex].sysClassificationList];

    [self refreshParam];
    [self request_goodsList];

}

#pragma mark- 协议方法
//collectionView的协议方法
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    return self.dataArray.count;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {

    ProductDetailViewController *vc = [[ProductDetailViewController alloc] init];
    vc.goodsId = self.dataArray[indexPath.row].goodsId;
    [self.navigationController pushViewController:vc animated:YES];
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    MarriageProductCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"MarriageProductCellID" forIndexPath:indexPath];
    [cell fillCellWithModel:self.dataArray[indexPath.row]];
    
    WEAKSELF
    cell.MarriageProductLoginBlock = ^{

        [weakSelf openLoginWithCompletion:^(BOOL isLogin, NSDictionary * _Nonnull options) {
            if (isLogin) {
                [weakSelf.collectionView reloadData];
            }
        }];
        
    };
    
    return cell;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    
    UICollectionReusableView *reusableView = nil;
    // 区头
    if (kind == UICollectionElementKindSectionHeader) {
        UICollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"UICollectionElementKindSectionHeader" forIndexPath:indexPath];
        reusableView = headerView;
    }
    // 区尾
    if (kind == UICollectionElementKindSectionFooter) {
        UICollectionReusableView *footerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"UICollectionElementKindSectionFooter" forIndexPath:indexPath];
        reusableView = footerView;
    }
    return reusableView;
}

//ZZLyout的流协议方法
- (CGFloat)layout:(ZZLayout *)layout heightForRowAtIndexPath:(NSIndexPath *)indexPath {//返回item的高
    return [MarriageProductCell calculateHeightWithWidth:TTScreenWidth-118];
}

- (NSInteger)layout:(ZZLayout *)layout columnNumberAtSection:(NSInteger)section {//每个区有几列
    return 2;
}

- (UIEdgeInsets)layout:(ZZLayout *)layout insetForSectionAtIndex:(NSInteger)section {//设置每个区的边距
    
    return UIEdgeInsetsMake(15, 15, 15, 15);
}

- (NSInteger)layout:(ZZLayout *)layout lineSpacingForSectionAtIndex:(NSInteger)section {//设置每个区的行间距

    return 10;
}

- (CGFloat)layout:(ZZLayout*)layout interitemSpacingForSectionAtIndex:(NSInteger)section {//设置每个区的列间距
    return 10;
}

- (CGSize)layout:(ZZLayout *)layout referenceSizeForHeaderInSection:(NSInteger)section {//设置区头的高度
    return CGSizeMake(TTScreenWidth, CGFLOAT_MIN);
}

- (CGSize)layout:(ZZLayout *)layout referenceSizeForFooterInSection:(NSInteger)section {//设置区尾的高度
    return CGSizeMake(TTScreenWidth, CGFLOAT_MIN);
}

- (CGFloat)layout:(ZZLayout*)layout spacingWithLastSectionForSectionAtIndex:(NSInteger)section {//本区区头和上个区区尾的间距
    return 0;
}

- (UIColor *)layout:(UICollectionView *)layout colorForSection:(NSInteger)section {//设置不同分区的不同背景颜色
    return [UIColor whiteColor];
}


#pragma mark- 懒加载
- (UICollectionView *)collectionView {
    if (!_collectionView) {
        
        ZZLayout *layout = [[ZZLayout alloc] initWith:ZZLayoutFlowTypeVertical delegate:self];
        //打开区头悬浮功能(默认关闭)
        layout.sectionHeadersPinToVisibleBounds = YES;
        
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
        _collectionView.backgroundColor = UIColorHex(0xffffff);
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        
        [_collectionView registerNib:[UINib nibWithNibName:@"MarriageProductCell" bundle:nil] forCellWithReuseIdentifier:@"MarriageProductCellID"];

        [_collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"UICollectionElementKindSectionHeader"];
        
        [_collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"UICollectionElementKindSectionFooter"];
        
        _collectionView.showsHorizontalScrollIndicator = NO;
        _collectionView.showsVerticalScrollIndicator = NO;

        _collectionView.bounces = YES;
        self.edgesForExtendedLayout = UIRectEdgeNone;
        if (@available(iOS 11.0, *)) {
            _collectionView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        
        WEAKSELF
        _collectionView.mj_footer = [MJRefreshBackGifFooter footerWithRefreshingBlock:^{

            weakSelf.pageNum++;
            [weakSelf request_goodsList];
        }];
        
    }
    return _collectionView;
}

- (PrimaryClassificationView *)primaryClassificationView {
    if (!_primaryClassificationView) {
        _primaryClassificationView = [[NSBundle mainBundle] loadNibNamed:@"PrimaryClassificationView"owner:nil options:nil].firstObject;
    }
    return _primaryClassificationView;
}

- (SecondaryClassificationView *)secondaryClassificationView {
    if (!_secondaryClassificationView) {
        _secondaryClassificationView = [[NSBundle mainBundle] loadNibNamed:@"SecondaryClassificationView"owner:nil options:nil].firstObject;
    }
    return _secondaryClassificationView;
}

- (CategoryNaviView *)naviView {
    if (!_naviView) {
        _naviView = [[NSBundle mainBundle] loadNibNamed:@"CategoryNaviView"owner:nil options:nil].firstObject;
        _naviView.searchTF.delegate = self;
    }
    return _naviView;
}

- (NSMutableArray<ProClassificationModel *> *)classificationDataArray {
    
    if (!_classificationDataArray) {
        _classificationDataArray = @[].mutableCopy;
    }
    return _classificationDataArray;
}

- (NSMutableArray<CommonPackageModel *> *)dataArray {
    if (!_dataArray) {
        _dataArray = @[].mutableCopy;
    }
    return _dataArray;
}

- (void)request_catData {
    NSMutableDictionary *dic = @{}.mutableCopy;

    [dic setValue:@"2" forKey:@"scType"];
    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,API_Category];
    
    WEAKSELF
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
        
        if ([data isKindOfClass:[NSDictionary class]]) {

            //请求成功
            NSInteger code = [[data valueForKey:@"code"] integerValue];
            if (code == 10000) {
                NSDictionary *resultDic = [data valueForKey:@"data"];
                if (![resultDic isKindOfClass:[NSDictionary class]]) {
                    return;
                }
                NSArray *oneList = [resultDic valueForKey:@"sysClassificationList"];
                if ([oneList isKindOfClass:[NSArray class]]) {
                    
                    self.classificationDataArray = @[].mutableCopy;
                    for (int i = 0; i < oneList.count; i++) {
                        ProClassificationModel *oneModel = [ProClassificationModel modelWithDictionary:oneList[i]];

                        if (i==0) {
                            oneModel.isSelect = YES;
                        }
                        
                        NSArray *twoList = [oneList[i] valueForKey:@"sysClassificationList"];
                        oneModel.sysClassificationList = @[].mutableCopy;
                        if ([twoList isKindOfClass:[NSArray class]]) {
                            
                            for (int j = 0; j < twoList.count; j++) {
                                ProClassificationModel *twoModel = [ProClassificationModel modelWithDictionary:twoList[j]];
                                NSArray *threeList = [twoList[j] valueForKey:@"sysClassificationList"];
                                
                                if (j==0) {
                                    twoModel.isSelect = YES;
                                }
                                
                                twoModel.sysClassificationList = @[].mutableCopy;
                                
                                if ([threeList isKindOfClass:[NSArray class]]) {
                                    for (int k = 0; k < threeList.count; k++) {
                                        ProClassificationModel *threeModel = [ProClassificationModel modelWithDictionary:threeList[k]];
                                        [twoModel.sysClassificationList addObject:threeModel];
                                    }
                                }
                                [oneModel.sysClassificationList addObject:twoModel];
                            }
                        }
                        [weakSelf.classificationDataArray addObject:oneModel];
                    }
                    [weakSelf.primaryClassificationView fillWithArray:weakSelf.classificationDataArray];
                    
                    if (weakSelf.classificationDataArray.count > 0) {
                        [weakSelf.secondaryClassificationView fillWithArray:weakSelf.classificationDataArray[0].sysClassificationList];

                        //如果二级分类有数据，请求商品列表
                        if (weakSelf.classificationDataArray.firstObject.sysClassificationList.count > 0) {
                            [weakSelf request_goodsList];
                        }
                    }
                }
            }
        }
                
    } FailedBlock:^(NSError * _Nonnull error) {
        
    }];
    
}


- (void)request_goodsList {
    
    NSMutableDictionary *dic = @{}.mutableCopy;

    [dic setValue:@(self.pageNum) forKey:@"pageNum"];
    [dic setValue:@(self.pageSize) forKey:@"pageSize"];
    
    ProClassificationModel *firModel = [ProClassificationModel new];
    if (self.classificationDataArray.count > self.firSelectIndex) {
        firModel = self.classificationDataArray[self.firSelectIndex];
    }
    
    ProClassificationModel *secModelModel = [ProClassificationModel new];
    if (firModel.sysClassificationList.count > self.secSelectIndex) {
        secModelModel = firModel.sysClassificationList[self.secSelectIndex];
    }

    NSMutableDictionary *t = @{}.mutableCopy;
    [t setValue:@"2" forKey:@"goodsMold"];
    [t setValue:@(secModelModel.scId) forKey:@"goodsType"];
    
//    [t setValue:@(1) forKey:@"goodsType"];
    [dic setValue:t forKey:@"t"];

    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,API_StorePackage];
    
    WEAKSELF
    [SVProgressHUD showWithStatus:@"正在加载"];
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
        
        [SVProgressHUD dismiss];
        [weakSelf.collectionView.mj_footer endRefreshing];
        
        if ([data isKindOfClass:[NSDictionary class]]) {

            //请求成功
            NSInteger code = [[data valueForKey:@"code"] integerValue];
            if (code == 10000) {
                NSDictionary *resultDic = [data valueForKey:@"data"];
                if (![resultDic isKindOfClass:[NSDictionary class]]) {
                    return;
                }
                NSArray *list = [resultDic valueForKey:@"list"];
                
                if ([list isKindOfClass:[NSArray class]]) {
                    
                    if (weakSelf.pageNum == 1) {
                        weakSelf.dataArray = @[].mutableCopy;
                    }
                    
                    for (int i = 0; i < list.count; i++) {
                        NSDictionary *listDic = list[i];
                        if ([listDic isKindOfClass:[NSDictionary class]]) {
                            CommonPackageModel *model = [CommonPackageModel modelWithJSON:list[i]];

                            [weakSelf.dataArray addObject:model];
                        }
                    }
                    [weakSelf.collectionView reloadData];
                }
            }
        }
        
    } FailedBlock:^(NSError * _Nonnull error) {
        
        [SVProgressHUD dismiss];
        [weakSelf.collectionView.mj_footer endRefreshing];

    }];
    
}

@end
